package com.opd.soeghtool;

import android.util.Log;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.Socket;
import java.net.UnknownHostException;

public class TcpSocketHelper {
    //IP地址
    private String address;
    //端口
    private int port;
    private byte g_u8Data[];
    private int g_s16DataLength=0;
    private Socket socket = null;
    private boolean bFinishFlag = false;
    private boolean bConnectedFlag = false;

    InputStream inputStream;
    OutputStream outputStream;

    TcpSocketHelper(String IP, int port)
    {
        g_u8Data = new byte[1024];
        this.address = IP;
        this.port = port;
    }
    private void LongToByte(long src, byte[] tar, int start) {
        tar[start] = (byte) (src & 0xFF);
        tar[start + 1] = (byte) ((src & 0xFF00) >> 8);
        tar[start + 2] = (byte) ((src & 0xFF0000) >> 16);
        tar[start + 3] = (byte) ((src & 0xFF000000) >> 24);
    }
    //TCP数据发送
    public void sendMessage(long command,long arg0, long arg1, long length, byte[] data){
        long u32Magic,u32Sum=0;
        LongToByte(command,g_u8Data,0);
        LongToByte(arg0,g_u8Data,4);
        LongToByte(arg1,g_u8Data,8);
        LongToByte(length,g_u8Data,12);

        for(int a=0; a<length;a++)
            u32Sum+= data[a];
        LongToByte(u32Sum,g_u8Data,16);
        u32Magic = ~command;
        LongToByte(u32Magic,g_u8Data,20);
        if((length>0)&&(data!=null))
            System.arraycopy(data,0,g_u8Data,24,(int)length);
        g_s16DataLength = (int)(24+ length);


        String aaa="Send: ";
        for(int k=0;k<g_s16DataLength;k++) {
            aaa += String.format("0x%x, ", g_u8Data[k] & 0xff);
            if((k%16)==15)
            {
                Log.d("SOE", aaa);
                aaa="";
            }
        }
        Log.d("SOE", aaa);
        Log.d("SOE","send: "+(new String(g_u8Data,0,g_s16DataLength)));
        Thread t = new TcpSendThread();
        t.start();
    }
    //发送数据线程
    public class TcpSendThread extends Thread{
        @Override
        public void run() {
            try {
                outputStream.write(g_u8Data,0,g_s16DataLength);
                outputStream.flush();
                //outputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    public void receiveMessage(final OnReceiveListener listener) {
        new Thread() {
            public void run() {
                        try {
                        while(!bConnectedFlag);
                        Log.d("SOE","11111111111");
                            byte[] bytes = new byte[1024];
                            int len=0;
                        while (!bFinishFlag) {
                            //while (inputStream.available() <= 0); // 过滤空消息

                            len = inputStream.read(bytes);
                            //StringBuffer stringBuffer = new StringBuffer();

                            if (len>0) {
                                //stringBuffer.append(new String(bytes, 0, len));

                                String aaa="Recv: ";
                                for(int k=0;k<len;k++) {
                                    aaa += String.format("0x%x, ", bytes[k] & 0xff);
                                    if((k%16)==15)
                                    {
                                        Log.d("SOE", aaa);
                                        aaa="";
                                    }
                                }
                                Log.d("SOE", aaa);


                                Log.d("SOE","Recv: "+(new String(bytes,0,len)));
                                listener.onDataReceive(bytes,len);
                            }
                            /*
                            if(len>0) {
                                String fromClient = stringBuffer.toString();
                                Log.d("SOE", fromClient);
                                listener.onDataReceive(fromClient);
                            }
                            */
                        }
                        Log.d("SOE","Finish");
                            inputStream.close();
                            outputStream.close();
                            socket.close();
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
            }
        }.start();
    }
    public interface OnReceiveListener {
        void onDataReceive(byte [] data,int len);
    }

    public class SocketConnectThread extends Thread
    {
        @Override
        public void run() {
            try {
                socket = new Socket(address, port);
                if(socket != null){
                    outputStream = socket.getOutputStream();
                    inputStream = socket.getInputStream();
                    bConnectedFlag = true;
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    public void connectSocket()
    {
        Thread thread =new SocketConnectThread();
        thread.start();
    }

    public void disconnectSocket()
    {
        bFinishFlag = true;
        bConnectedFlag =false;
        Log.d("SOE","Finish cmd");
    }
}
